package net.elive.peer.http;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import net.elive.peer.p2p.P2PAP;
import net.elive.tools.Contants;
import net.elive.tools.RandomNum;
import net.elive.utils.LogUtils;

import org.apache.commons.logging.Log;

/**
 * 本地的http服务器
 * @author caojin
 *
 */
public class HttpServer implements Runnable{
	Log log = LogUtils.getLog(HttpServer.class);
	private  ServerSocket ss = null;
	private Thread thread;
	public HttpServer(){
		int i=0;
		while(i<10&&true){
			i++;
			try {
				ss = new ServerSocket(Contants.LOCALHTTPPORT);
				thread = new Thread(this);
				thread.start();		//启动线程
				log.info(">>>>启动本地Http服务器成功>>>>端口号"+Contants.LOCALHTTPPORT);
				break;
			} catch (IOException e) {
				/**
				 * 启动失败重新生成随机数
				 */
				Contants.LOCALHTTPPORT =RandomNum.randomInt(256*256);
				log.info(">>>>启动本地Http服务器失败,重新启动中>>>>端口号:"+Contants.LOCALHTTPPORT);
				continue;
			}
		}
	}
	
	@Override
	public void run() {
		while(true){
			try {
				Socket socket = ss.accept();
				P2PAP.httpThreadPool.execute(new HttpRequest(socket));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
